/**
 * Title: LoginActivity.java
 * Description:
 * author: kotomifi
 * date: Jul 6, 2014
 * ©2014 apping 社区
 */
package com.apping.demo.bbs;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.sina.weibo.sdk.demo.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apping.demo.bbs.bean.LoginJson;
import com.apping.demo.bbs.global.AccessTokenKeeper;
import com.apping.demo.bbs.global.Constants;
import com.apping.demo.bbs.utils.HttpTools;
import com.apping.demo.bbs.utils.NetCheck;
import com.apping.demo.bbs.utils.SharedPreferencesUtil;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.umeng.analytics.MobclickAgent;

/**
 *
 */
public class LoginActivity extends Activity {

	private Intent m_intent;
	private Class<?> m_cls;
	private WeiboAuth mWeiboAuth;
	private Oauth2AccessToken mAccessToken;
	private String loginStr;
	
	private static final int LOGIN_SUCCESS = 1;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOGIN_SUCCESS:
				parsingLoginStr();
				break;
			}
		}
	};
	
	/**
	 * 解析登陆请求返回json
	 * 登陆成功并将ticket和uid保存到SharedPerferences:com_apping_demo_bbs
	 * 登陆失败给出提示，停留在登陆页面
	 */
	private void parsingLoginStr() {
		String rst = JSON.parseObject(loginStr).getString("rst");
		if (rst.equals("SUCCESS")) {
			LoginJson loginJson = JSON.parseObject(loginStr, LoginJson.class);
			
			SharedPreferencesUtil preferences = new SharedPreferencesUtil(getApplication());
			preferences.writeString("com_apping_demo_bbs", "ticket", 
					loginJson.getMsg().getTicket());
			preferences.writeLong("com_apping_demo_bbs", "uid", 
					loginJson.getMsg().getUid());
			setNextActivity(ArticleActivity.class);
			nextActivity();
			finish();
		} else {
			Toast.makeText(LoginActivity.this, 
					"登陆失败，请重新登陆", 2000).show();
		}	
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onPageStart("SplashScreen"); //统计页面
	    MobclickAgent.onResume(this);          //统计时长
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPageEnd("SplashScreen"); // 保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
	    MobclickAgent.onPause(this);
	}
	
	public void nextActivity() {
		m_intent.setClass(getApplication(), m_cls);
		startActivity(m_intent);
	}

	public void setNextActivity(Class<?> cls) {
		m_cls = cls;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		m_intent = new Intent();
		mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY,Constants.REDIRECT_URL, Constants.SCOPE);
		setContentView(R.layout.login_activity);
		initUI();
	}
	
	public void initUI() {
		LinearLayout linearLayout = (LinearLayout)findViewById(R.id.login_with_weibo);
		linearLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mWeiboAuth.anthorize(new AuthListener());
			}
		});
	}
	
	/**
	 * 向服务器发送登陆请求
	 */
	private void sendLogin() {
		if (NetCheck.isNetworkConnected(this)) {
			new Thread() {
				@Override
				public void run() {
					SharedPreferencesUtil prefernces = new SharedPreferencesUtil(getApplication());
//					String token = prefernces.readString(
//							"com_weibo_sdk_android", "access_token");
//					String uid = prefernces.readString("com_weibo_sdk_android", "uid");
//					String url = "http://42.96.192.37:8080/apping/demo/login?token="
//							+ token + "&&uid=" + uid + "&&channel=weibo";
					
					// 以下为测试URL，实际情况请使用上面的URL
					String token = "nimeinimeide";
					String url = "http://42.96.192.37:8080/apping/demo/login?token="
							+ token + "&&uid=weibo_cz" + "&&channel=weibo";
					HttpTools httpTool = new HttpTools();
					try {
						httpTool.get(url);
					} catch (Exception e) {
						e.printStackTrace();
					}
					loginStr = httpTool.getContent();
					Log.i("TAG==", loginStr);
					// 发送消息通知UI线程更新UI组建
					handler.sendEmptyMessage(LOGIN_SUCCESS);
				}
			}.start();
		} else {
			Toast.makeText(LoginActivity.this, 
					"无法连接到网络，请检查网络", 2000).show();
		}
	}
	
	class AuthListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                // 显示 Token
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(LoginActivity.this, mAccessToken);
                Toast.makeText(LoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                //Toast.makeText(LoginActivity.this, mAccessToken.toString(), Toast.LENGTH_LONG).show();
                // 发送登陆请求
                sendLogin();
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = "获取token失败";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(LoginActivity.this,"授权取消", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(LoginActivity.this, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
	}

}
